package net.zhuike.novel.app.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;


import com.umeng.analytics.MobclickAgent;

import net.zhuike.novel.app.R;
import net.zhuike.novel.app.bean.CollBookBean;
import net.zhuike.novel.app.bean.local.BookRepository;
import net.zhuike.novel.app.ui.base.Constant;
import net.zhuike.novel.app.ui.fragment.BaseFileFragment;
import net.zhuike.novel.app.ui.fragment.FileCategoryFragment;
import net.zhuike.novel.app.ui.fragment.LocalBookFragment;
import net.zhuike.novel.app.ui.utils.StringUtils;
import net.zhuike.novel.app.ui.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import framework.common.baseui.UeBaseActivity;

/**
 * Created by wq
 * 本地导入
 */

public class FileSystemActivity extends UeBaseActivity {
    private static final String TAG = "FileSystemActivity";

    @Bind(R.id.file_system_cb_selected_all)
    CheckBox mCbSelectAll;
    @Bind(R.id.file_system_btn_delete)
    Button mBtnDelete;
    @Bind(R.id.file_system_btn_add_book)
    Button mBtnAddBook;
    @Bind(R.id.tab_tl_indicator)
    TabLayout mTlIndicator;
    @Bind(R.id.tab_vp)
    ViewPager mVp;
    /************Params*******************/
    private List<Fragment> mFragmentList;
    private List<String> mTitleList;
   // private LocalBookFragment mLocalFragment;
    private FileCategoryFragment mCategoryFragment;
    private BaseFileFragment mCurFragment;
   private Context mContext;
    private BaseFileFragment.OnFileCheckedListener mListener = new BaseFileFragment.OnFileCheckedListener() {
        @Override
        public void onItemCheckedChange(boolean isChecked) {
            changeMenuStatus();
        }

        @Override
        public void onCategoryChanged() {
            //状态归零
            mCurFragment.setCheckedAll(false);
            //改变菜单
            changeMenuStatus();
            //改变是否能够全选
            changeCheckedAllStatus();
        }
    };

    protected List<Fragment> createTabFragments() {
       // mLocalFragment = new LocalBookFragment();
        mCategoryFragment = new FileCategoryFragment();
        return Arrays.asList(mCategoryFragment);
    }


    protected List<String> createTabTitles() {
        return Arrays.asList("手机目录");
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_file_system);
        hiddenFooter();
        showGoBackBtn();
        setTitleText("本地导入");
        mContext = this;
        //获取页面加载器
        setUpTabLayout();
        processLogic();
        initClick();
    }
    protected void setUpToolbar(Toolbar toolbar) {
        getSupportActionBar().setTitle("本机导入");
    }
    protected void initClick() {
        mCbSelectAll.setOnClickListener(
                (view) -> {
                    //设置全选状态
                    boolean isChecked = mCbSelectAll.isChecked();
                    mCurFragment.setCheckedAll(isChecked);
                    //改变菜单状态
                    changeMenuStatus();
                }
        );

        mVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mCurFragment = mCategoryFragment;
                //改变菜单状态
                changeMenuStatus();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mBtnAddBook.setOnClickListener(
                (v) -> {
                    //获取选中的文件
                    List<File> files = mCurFragment.getCheckedFiles();
                    //转换成CollBook,并存储
                    List<CollBookBean> collBooks = convertCollBook(files);
                    BookRepository.getInstance()
                            .saveCollBooks(collBooks);
                    //设置HashMap为false
                    mCurFragment.setCheckedAll(false);
                    //改变菜单状态
                    changeMenuStatus();
                    //改变是否可以全选
                    changeCheckedAllStatus();
                    //提示加入书架成功
                    ToastUtils.showToast(getResources().getString(R.string.nb_file_add_succeed,collBooks.size()));

                }
        );

        mBtnDelete.setOnClickListener(
                (v) -> {
                    //弹出，确定删除文件吗。
                    new AlertDialog.Builder(this)
                            .setTitle("删除文件")
                            .setMessage("确定删除文件吗?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //删除选中的文件
                                    mCurFragment.deleteCheckedFiles();
                                    //提示删除文件成功
                                    ToastUtils.showToast("删除文件成功");
                                }
                            })
                            .setNegativeButton("取消", null)
                            .show();
                }
        );

       // mLocalFragment.setOnFileCheckedListener(mListener);
        mCategoryFragment.setOnFileCheckedListener(mListener);
    }


    protected void processLogic() {
        mCurFragment = mCategoryFragment;
    }

    /**
     * 将文件转换成CollBook
     * @param files:需要加载的文件列表
     * @return
     */
    private List<CollBookBean> convertCollBook(List<File> files){
        List<CollBookBean> collBooks = new ArrayList<>(files.size());
        for(File file : files){
            //判断文件是否存在
            if (!file.exists()) continue;

            CollBookBean collBook = new CollBookBean();
            collBook.setLocal(true);
            collBook.setId(file.getAbsolutePath());
            collBook.setName(file.getName().replace(".txt",""));
            collBook.setChapterName("开始阅读");
            collBook.setLastestUpdateTime(StringUtils.
                    dateConvert(System.currentTimeMillis(), Constant.FORMAT_BOOK_DATE));
            collBooks.add(collBook);
        }
        return collBooks;
    }

    /**
     * 改变底部选择栏的状态
     */
    private void changeMenuStatus(){

        //点击、删除状态的设置
        if (mCurFragment.getCheckedCount() == 0){
            mBtnAddBook.setText(getString(R.string.nb_file_add_shelf));
            //设置某些按钮的是否可点击
            setMenuClickable(false);

            if (mCbSelectAll.isChecked()){
                mCurFragment.setChecked(false);
                mCbSelectAll.setChecked(mCurFragment.isCheckedAll());
            }

        }
        else {
            mBtnAddBook.setText(getString(R.string.nb_file_add_shelves,mCurFragment.getCheckedCount()));
            setMenuClickable(true);

            //全选状态的设置

            //如果选中的全部的数据，则判断为全选
            if (mCurFragment.getCheckedCount() == mCurFragment.getCheckableCount()){
                //设置为全选
                mCurFragment.setChecked(true);
                mCbSelectAll.setChecked(mCurFragment.isCheckedAll());
            }
            //如果曾今是全选则替换
            else if (mCurFragment.isCheckedAll()){
                mCurFragment.setChecked(false);
                mCbSelectAll.setChecked(mCurFragment.isCheckedAll());
            }
        }

        //重置全选的文字
        if (mCurFragment.isCheckedAll()){
            mCbSelectAll.setText("取消");
        }
        else {
            mCbSelectAll.setText("全选");
        }

    }

    private void setMenuClickable(boolean isClickable){

        //设置是否可删除
        mBtnDelete.setEnabled(isClickable);
        mBtnDelete.setClickable(isClickable);

        //设置是否可添加书籍
        mBtnAddBook.setEnabled(isClickable);
        mBtnAddBook.setClickable(isClickable);
    }

    /**
     * 改变全选按钮的状态
     */
    private void changeCheckedAllStatus(){
        //获取可选择的文件数量
        int count = mCurFragment.getCheckableCount();

        //设置是否能够全选
        if (count > 0){
            mCbSelectAll.setClickable(true);
            mCbSelectAll.setEnabled(true);
        }
        else {
            mCbSelectAll.setClickable(false);
            mCbSelectAll.setEnabled(false);
        }
    }
    private void setUpTabLayout(){
        mFragmentList = createTabFragments();
        mTitleList = createTabTitles();

        checkParamsIsRight();

        TabFragmentPageAdapter adapter = new TabFragmentPageAdapter(getSupportFragmentManager());
        mVp.setAdapter(adapter);
        mVp.setOffscreenPageLimit(3);
        mTlIndicator.setupWithViewPager(mVp);
    }

    /**
     * 检查输入的参数是否正确。即Fragment和title是成对的。
     */
    private void checkParamsIsRight(){
        if (mFragmentList == null || mTitleList == null){
            throw new IllegalArgumentException("fragmentList or titleList doesn't have null");
        }

        if (mFragmentList.size() != mTitleList.size())
            throw new IllegalArgumentException("fragment and title size must equal");
    }

    /******************inner class*****************/
    class TabFragmentPageAdapter extends FragmentPagerAdapter {

        public TabFragmentPageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position);
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("本地导入");
        MobclickAgent.onResume(context);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("本地导入");
        MobclickAgent.onPause(context);
    }
}
